package cn.cdeden.system.service.impl;

import cn.cdeden.common.core.constant.CacheNames;
import cn.cdeden.common.core.exception.ServiceException;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.cdeden.common.redis.utils.CacheUtils;
import cn.cdeden.system.domain.SysLargeModel;
import cn.cdeden.system.domain.SysLgtypeConfig;
import cn.cdeden.system.domain.bo.SysLargeModelBo;
import cn.cdeden.system.domain.vo.SysLargeModelVo;
import cn.cdeden.system.mapper.SysLargeModelMapper;
import cn.cdeden.system.service.ISysLargeModelService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@Service
public class SysLargeModelServiceImpl implements ISysLargeModelService {

    private final SysLargeModelMapper baseMapper;


    @Override
    public TableDataInfo<SysLargeModelVo> queryPageList(SysLargeModelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysLargeModel> lqw = buildQueryWrapper(bo);
        Page<SysLargeModelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<SysLargeModelVo> queryList(SysLargeModelBo bo) {
        LambdaQueryWrapper<SysLargeModel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public SysLargeModelVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    @Cacheable(cacheNames = CacheNames.SYS_LARGE_MODEL, key = "#configKey")
    @Override
    public String selectConfigByKey(String configKey) {
        SysLargeModel retConfig = baseMapper.selectOne(new LambdaQueryWrapper<SysLargeModel>()
            .eq(SysLargeModel::getConfigKey, configKey));
        if (ObjectUtil.isNotNull(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

//    @Cacheable(cacheNames = CacheNames.SYS_LARGE_MODEL, key = "#configKey")
    @Override
    public String selectConfigByTypeKey(String configKey, String configType) {
        SysLargeModel retConfig = baseMapper.selectOne(new LambdaQueryWrapper<SysLargeModel>()
            .eq(SysLargeModel::getConfigKey, configKey)
            .eq(SysLargeModel::getLargeModelType, configType));
        if (ObjectUtil.isNotNull(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }



    @Override
    public boolean checkConfigKeyUnique(SysLargeModelBo config) {
        long configId = ObjectUtil.isNull(config.getId()) ? -1L : config.getId();
        SysLargeModel info = baseMapper.selectOne(new LambdaQueryWrapper<SysLargeModel>().eq(SysLargeModel::getConfigKey, config.getConfigKey()));
        if (ObjectUtil.isNotNull(info) && info.getId() != configId) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkConfigDefault(SysLargeModelBo config) {
        long configId = ObjectUtil.isNull(config.getId()) ? -1L : config.getId();
        SysLargeModel aTrue = baseMapper.selectOne(new LambdaQueryWrapper<SysLargeModel>().eq(SysLargeModel::getDefaultOptions, "true"));
        if (ObjectUtil.isNotNull(aTrue) && aTrue.getId() != configId) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean insertByBo(SysLargeModelBo bo) {
        SysLargeModel add = MapstructUtils.convert(bo, SysLargeModel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @CachePut(cacheNames = CacheNames.SYS_LARGE_MODEL, key = "#bo.configKey")
    public String updateByBo(SysLargeModelBo bo) {
        SysLargeModel update = MapstructUtils.convert(bo, SysLargeModel.class);
        validEntityBeforeSave(update);
        baseMapper.updateById(update);
        return update.getConfigValue();
    }

    @CachePut(cacheNames = CacheNames.SYS_LARGE_MODEL, key = "#bo.configKey")
    @Override
    public String updateConfig(SysLargeModelBo bo) {
        int row = 0;
        SysLargeModel config = MapstructUtils.convert(bo, SysLargeModel.class);
        if (config.getId() != null) {
            SysLargeModel temp = baseMapper.selectById(config.getId());
            if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
                CacheUtils.evict(CacheNames.SYS_LARGE_MODEL, temp.getConfigKey());
            }
            row = baseMapper.updateById(config);
        } else {
            CacheUtils.evict(CacheNames.SYS_LARGE_MODEL, config.getConfigKey());
            row = baseMapper.update(config, new LambdaQueryWrapper<SysLargeModel>()
                .eq(SysLargeModel::getConfigKey, config.getConfigKey()));
        }
        if (row > 0) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void resetConfigCache() {
        CacheUtils.clear(CacheNames.SYS_LARGE_MODEL);
    }

    @Override
    public SysLargeModel selectRemoteDefault() {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysLargeModel>().eq(SysLargeModel::getDefaultOptions, "true"));
    }


    private LambdaQueryWrapper<SysLargeModel> buildQueryWrapper(SysLargeModelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysLargeModel> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getConfigName()), SysLargeModel::getConfigName, bo.getConfigName());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), SysLargeModel::getConfigKey, bo.getConfigKey());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigValue()), SysLargeModel::getConfigValue, bo.getConfigValue());
        lqw.eq(StringUtils.isNotBlank(bo.getLargeModelType()), SysLargeModel::getLargeModelType, bo.getLargeModelType());
        lqw.eq(bo.getUpdatedAt() != null, SysLargeModel::getUpdatedAt, bo.getUpdatedAt());
        return lqw;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysLargeModel entity){
        //TODO 做一些数据校验,如唯一约束
    }


}
